package com.example.demo.config;

import org.springframework.util.DigestUtils;

import java.util.UUID;

public class EncrypTool {

    /**
     * 加密
     * @return
     */
    public static String encryp(String inputPassword) {
        String salt = UUID.randomUUID().toString().replace("-", "");
        String start = DigestUtils.md5DigestAsHex((salt + inputPassword).getBytes());
        String end = salt + "$" + start;
        return end;
    }

    /**
     * 对照
     * @param salt
     * @param inputPassword
     * @return
     */
    private static String encryp(String salt, String inputPassword) {
        String start = DigestUtils.md5DigestAsHex((salt + inputPassword).getBytes());
        String end = salt + "$" + start;
        return end;
    }

    public static boolean check(String inputPassword, String finalPassword) {
        if(inputPassword == null || finalPassword == null ||
                finalPassword.length() != 65) {
            return false;
        }
        String salt = finalPassword.split("\\$")[0];
        return finalPassword.equals(encryp(salt, inputPassword));
    }

}

//class Main {
//    public static void main(String[] args) {
//        String input1 = "123";
//        String input2 = "1234";
//        String end1 = EncrypTool.encryp(input1);
//        String end2 = EncrypTool.encryp(input2);
//        System.out.println(end1);
//        System.out.println(end2);
//        System.out.println("----------------------------------");
//        System.out.println(EncrypTool.check(input1, end1));
//        System.out.println(EncrypTool.check(input2, end1));
//    }
//}
